跳到主要内容

Java资源路径、字符串操作、位操作相关

字符串常用操作

这里记录一些常用的操作,以免忘记

分割字符

public String[] split(String regex, int limit)
  • regex -- 正则表达式分隔符。
  • limit -- 分割的份数。

使用例:

public static void main(String[] args) {
String str = "one two three, four";
String[] tokens = str.split(" ");
for (String s: tokens)
System.out.println(s);
}
String address="上海@上海市@闵行区@吴中路";
String[] splitAddress=address.split("@");
System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);

系统换行符

Windows: \r\n linux: /n mac: /r

//直接获取系统换行符
System.lineSeparator();

正则表达式

一般使用正则表达式都是使用这个 Pattern 工具类

import java.util.regex.*;

class RegexExample1{
public static void main(String[] args){
String content = "I am alsritter " +
"from alsritter.icu.";

String pattern = ".*alsritter.*";

boolean isMatch = Pattern.matches(pattern, content);
System.out.println("字符串中是否包含了 'alsritter' 子字符串? " + isMatch);
}
}

取得匹配到的值

// 对这一行正则
Pattern p = Pattern.compile("https://i.loli.net/.*");
Matcher matcher = p.matcher(line);
while (matcher.find()) {
System.out.println(matcher.group()); // 获得匹配的地址
}

字符替换

public class StringReplaceEmp{
public static void main(String args[]){
String str="Hello World";
System.out.println( str.replace( 'H','W' ) );
System.out.println( str.replaceFirst("He", "Wa") );
System.out.println( str.replaceAll("He", "Ha") );
}
}

输出结果

Wello World
Wallo World
Hallo World

StringBuffer 和 StringBuilder

参考资料 java中String、StringBuffer和StringBuilder的区别(简单介绍)

  • String:适用于少量的字符串操作的情况
  • StringBuilder:适用于单线程下在字符缓冲区进行大量操作的情况
  • StringBuffer:适用多线程下在字符缓冲区进行大量操作的情况

TODO: 学完数据结构和多线程再回来补这块

枚举与位操作

采用位运算进行分类

假设一种场景,如果你想用 一个数表示多种状态,那么位运算是一种很好的选择(或者使用 EnumSet)。用或运算复合多种状态,用与运算判断是否包含某种状态。

注意 Java 的语法不支持枚举直接映射到值上,所以需要使用静态类



static class Color{
static final Integer
BLACK = 0<<0,
RED = 1<<0,
BLUE = 1<<1,
GREEN = 1<<2 ,
YELLOW = 1<<3;
}
public static void main(String[] args) {
testEnum(Color.GREEN | Color.RED | Color.YELLOW);
}
private static void testEnum(Integer _enum){
//注意这里不能使用switch,因为是需要按顺序执行if
if (_enum == 0){
System.out.println("BLACK");
}
if ((_enum & Color.RED)>0){
System.out.println("RED");
}
if ((_enum & Color.BLUE)>0){
System.out.println("BLUE");
}
if ((_enum & Color.GREEN)>0){
System.out.println("GREEN");
}
if ((_enum & Color.YELLOW)>0){
System.out.println("YELLOW");
}
}

原理就是用 2 的幂(即1 2 4 8 等)相加后二进制会不同

这里补充一个 C# 版的,相对而言使用枚举更加的优雅

private enum Color
{
Black = 0,
Red = 1<<0,
Green = 1<<1,
Blue = 1<<2,
Yellow = 1<<3,
}
static void Main(string[] args)
{
TestEnump(Color.Green | Color.Red | Color.Green | Color.Yellow);
Console.ReadKey();
}
private static void TestEnump(Color _enum)
{
if(_enum == 0)
{
Console.WriteLine("Black");
return;
}
if ((_enum & Color.Red) > 0)
{
Console.WriteLine("Red");
}
if ((_enum & Color.Green) > 0)
{
Console.WriteLine("Green");
}
if ((_enum & Color.Blue) > 0)
{
Console.WriteLine("Blue");
}
if ((_enum & Color.Yellow) > 0)
{
Console.WriteLine("Yellow");
}
}